<?php

namespace Lowpress\PressExtensionsBundle\Feeds;

use Lowpress\PressBundle\Feeds\IFeedGatherer,
    Symfony\Component\DependencyInjection\ContainerInterface,
    Lowpress\PressExtensionsBundle\Entity\YouTube;

class YouTubeFeedGatherer implements IFeedGatherer
{

  private $email;
  private $password;

  public function __construct($email, $password)
  {
    $this->email = $email;
    $this->password = $password;
  }

  public function gather(ContainerInterface $container)
  {
    // get doctrine, the repos, the em and the last entry
    $doctrine = $container->get("doctrine");
    $youtube_repository = $doctrine->getRepository('LowpressPressExtensionsBundle:YouTube');
    $em = $doctrine->getEntityManager();
    $last_tube = $youtube_repository->findOneBy(array(), array('created', 'DESC'));

    // get the youtube service
    $yt = $this->getYtService();
    $user = $yt->getUserProfile("default");
    // foreach of the feed entries
    foreach($yt->getActivityForUser($user->getUsername()) as $entry)
    {

      // get the date
      $entry_date = new \DateTime($entry->getUpdated()->text);

      // if there wasnt a last entry, or the last entrys date is smaller than this...
      if (!$last_tube || ($last_tube && $entry_date > $last_tube->getCreated()))
      {

        // and it has a video id..
        if ($video_id = $entry->getVideoId())
        {
          $video = $yt->getVideoEntry($video_id);


          // stick it in our database
          $tube = new YouTube();
          $tube->setYoutubeId($video_id->text);
          $tube->setCreated($entry_date);
          foreach ($video->getVideoTags() as $tag_name)
          {
            $tag = $doctrine->getRepository('LowpressPressBundle:Tag')->findOneByName($tag_name);
            if ($tag == null)
            {
              $tag = new \Lowpress\PressBundle\Entity\Tag();
              $tag->setName($tag_name);
              $tube->addTag($tag);
            }
            $em->persist($tag);
          }
          $em->persist($tube);
        }
      }
    }
    $em->flush();
  }


  private function getYtService()
  {
    $client = \Zend_Gdata_ClientLogin::getHttpClient($this->email, $this->password, 'youtube');
    $applicationId = "Lowpress";
    $devKey = "AI39si4QbihKDWmULNHFYoSipGeL5tfBbASD8wmW8-gjNJVPm9VAaqSqXCFfA1dXNImZnxmXnXzIi4xNeYrPf1sZJ3fEBGmElQ";
    $yt = new \Zend_Gdata_YouTube($client, $applicationId, null, $devKey);
    $yt->setMajorProtocolVersion(2);
    return $yt;
  }
}

?>